package com.gxuwz.stats.controller.twoAdmin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/twoUser")
public class UserTwoController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     * @param params 请求参数
     * @param currentPage 当前页码
     * @param pageSize    每页大小
     * @return
     */
    @GetMapping("/getUserList")
    public ResponseEntity<Map<String, Object>> userList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {

            // 提取 Token 并解析用户信息
            String token = authorization.replace("Bearer ", "");
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
//            int userId = jwtTokenUtil.getUserIdFromToken(token);
            String department = jwtTokenUtil.getDepartmentFromToken(token); // 获取部门信息

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<User> page = new Page<>(currentPage, pageSize);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();

// 如果是二级学院管理员，添加 department 过滤条件
            if (department != null && !department.isEmpty()) {
                queryWrapper.eq("department", department); // 只查询当前部门的数据
            }

            // 模糊查询条件
            if (params.containsKey("userKeyword") && !params.get("userKeyword").isEmpty()) {
                String keyword = "%" + params.get("userKeyword") + "%";
                queryWrapper.and(wrapper -> wrapper
                        .like("username", keyword)
                        .or().like("role", keyword)
                        .or().like("degree", keyword)
                        .or().like("position", keyword)
                        .or().like("post", keyword)
                        .or().like("department", keyword));
            }

            // 调用 service 层的分页查询方法
            IPage<User> resultPage = userService.page(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 导入用户表格数据
     * @param file
     * @param updateSupport
     * @return
     */
//    @PostMapping("/importData")
//    public ResponseEntity<Map<String, Object>> importData(
//            @RequestParam("file") MultipartFile file,
//            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) {
//        try {
//            List<User> users = userService.importExcel(file.getInputStream(), updateSupport);
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 200);
//            response.put("message", "导入成功");
//            response.put("data", users);
//            return ResponseEntity.ok(response);
//        } catch (Exception e) {
//            Map<String, Object> errorResponse = new HashMap<>();
//            errorResponse.put("code", 400);
//            errorResponse.put("message", "导入失败: " + e.getMessage());
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
//        }
//    }

    /**
     * 新增用户
     */
    @PostMapping("/addUser")
    public ResponseEntity<Map<String, Object>> addUser(@RequestBody User user) {
        System.out.println("user===" + user);
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        }
        userService.save(user);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/deleteUser")
    public ResponseEntity<Map<String, Object>> deleteUser(@RequestBody List<Long> userIds) {
        System.out.println("删除：" + userIds);
        userService.removeByIds(userIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改用户
     */
    @PutMapping("/editUser")
    public ResponseEntity<Map<String, Object>> editUser(@RequestBody User user) {
        System.out.println("user::" + user);

        userService.updateById(user);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 获取到当前登录的用户
     * @param authentication
     * @return
     */
//    @GetMapping("/current")
//    public ResponseEntity<Map<String, Object>> getCurrentUser(Authentication authentication) {
////        System.out.println("11111="+authentication);
//        if (authentication == null || !authentication.isAuthenticated()) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
//        }
//
//        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
//        System.out.println("当前登录："+userDetails);
//
//        String username = userDetails.getUsername();
//        System.out.println("username="+username);
//        int userId = userService.getUserIdByUsername(username);
//        Map<String, Object> response = new HashMap<>();
//        response.put("userId", userId);
//        response.put("username", userDetails.getUsername());
//        response.put("code", 200);
////        response.put("password", userDetails.getPassword());
//        return ResponseEntity.ok(response);
//
//
//    }
}

